import { AfterViewInit, Component, ElementRef, ViewChild } from '@angular/core';
import { CurveChart } from '@app/core/domain/dashboard';
import { DashboardService } from '@app/core/services/http/dashboard/dashboard.service';
import * as echarts from 'echarts';

@Component({
  selector: 'app-curve-chart',
  standalone: true,
  imports: [],
  templateUrl: './curve-chart.component.html',
  styleUrls: ['../dashboard.component.less', './curve-chart.component.less']
})
export class CurveChartComponent implements AfterViewInit {
  @ViewChild('curveChart') curveChart!: ElementRef<HTMLElement>;
  monthArray: string[] = [];

  constructor(private readonly dashboardService: DashboardService) {}

  initChart(averagefare: string[], averageHospitalizationDays: string[]): void {
    this.curveChart.nativeElement.innerHTML = '';
    var myChart = echarts.init(document.getElementById('curveChart'));
    const option: any = {
      tooltip: {
        trigger: 'axis'
      },
      grid: {
        left: '3%',
        right: '5%',
        top: '30px',
        bottom: '5%',
        containLabel: true
      },
      legend: {
        x: 'right',
        y: '2%',
        data: ['平均住院费用', '平均住院日'],
        icon: 'circle',
        textStyle: {
          color: '#fff'
        },
        itemGap: 12, //图例每项之间的间隔
        itemWidth: 5,
        itemHeight: 5
      },
      color: ['#a4d8cc', '#25f3e6'],
      toolbox: {
        show: false,
        feature: {
          mark: { show: true },
          dataView: { show: true, readOnly: false },
          magicType: { show: true, type: ['line', 'bar', 'stack', 'tiled'] },
          restore: { show: true },
          saveAsImage: { show: true }
        }
      },

      calculable: true,
      xAxis: [
        {
          type: 'category',
          axisTick: { show: false },
          boundaryGap: false,
          axisLabel: {
            rotate: 45,
            interval: 0,
            textStyle: {
              color: 'rgba(255,255,255,.6)',
              fontSize: '12'
            },
            lineStyle: {
              color: 'rgba(255,255,255,.1)'
            },
            //   rotate:50,
            formatter: function (params: any) {
              var newParamsName = ''; // 最终拼接成的字符串
              var paramsNameNumber = params.length; // 实际标签的个数
              var provideNumber = 8; // 每行能显示的字的个数
              var rowNumber = Math.ceil(paramsNameNumber / provideNumber); // 换行的话，需要显示几行，向上取整
              /**
               * 判断标签的个数是否大于规定的个数， 如果大于，则进行换行处理 如果不大于，即等于或小于，就返回原标签
               */
              // 条件等同于rowNumber>1
              if (paramsNameNumber > provideNumber) {
                /** 循环每一行,p表示行 */
                var tempStr = '';
                tempStr = params.substring(0, 4);
                newParamsName = `${tempStr}...`; // 最终拼成的字符串
              } else {
                // 将旧标签的值赋给新标签
                newParamsName = params;
              }
              //将最终的字符串返回
              return newParamsName;
            }
          },
          data: this.monthArray
        }
      ],
      yAxis: {
        min: 300,
        type: 'value',
        axisLabel: {
          textStyle: {
            color: '#ccc',
            fontSize: '12'
          }
        },
        axisLine: {
          lineStyle: {
            color: 'rgba(160,160,160,0.2)'
          }
        },
        splitLine: {
          lineStyle: {
            color: 'rgba(160,160,160,0.2)'
          }
        }
      },

      series: [
        {
          name: '平均住院费用',
          lineStyle: {
            color: 'rgb(2455,200,68)'
          },

          type: 'line',
          areaStyle: {
            normal: {
              type: 'default',
              color: new echarts.graphic.LinearGradient(
                0,
                0,
                0,
                0.8,
                [
                  {
                    offset: 0,
                    color: 'rgba(129,197,255,.6)'
                  },
                  {
                    offset: 1,
                    color: 'rgba(129,197,255,.0)'
                  }
                ],
                false
              )
            }
          },
          smooth: true,
          itemStyle: {
            normal: { areaStyle: { type: 'default' } }
          },
          data: averagefare
        },
        {
          name: '平均住院日',
          lineStyle: {
            color: 'rgb(108,244,252)'
          },

          type: 'line',
          areaStyle: {
            normal: {
              type: 'default',
              color: new echarts.graphic.LinearGradient(
                0,
                0,
                0,
                0.8,
                [
                  {
                    offset: 0,
                    color: 'rgba(129,197,255,.6)'
                  },
                  {
                    offset: 1,
                    color: 'rgba(129,197,255,.0)'
                  }
                ],
                false
              )
            }
          },
          smooth: true,
          itemStyle: {
            normal: { areaStyle: { type: 'default' } }
          },
          data: averageHospitalizationDays
        }
      ]
    };

    // 使用刚指定的配置项和数据显示图表。
    myChart.setOption(option);
  }

  initCurrentYearMonth(): void {
    const year = new Date().getFullYear();
    for (let index = 1; index <= 12; index++) {
      this.monthArray.push(`${year}-${index < 10 ? '0' + index : index}`);
    }
  }

  initChartData(): void {
    this.initCurrentYearMonth();
    this.dashboardService.getCurveChartData().subscribe((result: CurveChart) => {
      this.initChart(result.averagefare, result.averagehospitalizationdays);
    });
  }

  ngAfterViewInit(): void {
    this.initChartData();
  }
}
